import 'package:todo_app/controllers/definitions/MessageModel.dart';

extension MessageModelExt on MessageModel {
  DateTime? get sendDt {
    if(send_time == null) return null;
    return DateTime.fromMillisecondsSinceEpoch(send_time!);
  }

  // 五分钟内的聊天纳入到一起
  static int second = 300;
  // 是否是同一时间段
  static bool isSameSection(MessageModel a, MessageModel b) {
    if(a.send_time == null || b.send_time == null) return false;
    var aDt = a.sendDt;
    var bDt = b.sendDt;
    if(aDt == null || bDt == null) return false;
    return aDt.difference(bDt).inSeconds.abs() < second;
  }
}

// 本地存储消息格式
class LocalMessage extends MessageModel {
  // 是否正在发送
  bool? sending = false;
  // 是否发送失败
  bool? sendError = false;
  // 创建时间
  DateTime? createdAt;
  // 更新时间
  DateTime? updatedAt;
  // 消息属于者 避免切换用户时内容串
  int? userId;
  // 消息类型
  ViewMessageType? viewType;
  // 是否是段消息
  bool section = false;

  String get topic {
    return '/s/$suid/$rid';
  }

  DateTime? get sendDt {
    if(send_time == null) return null;
    return DateTime.fromMillisecondsSinceEpoch(send_time!);
  }

  // 判断是否是自己
  bool checkIsMe(num? meUid) {
    if(suid == null) return false;
    if(meUid == null) return false;
    return suid == meUid;
  }

  @override
  void fromJson(Map<String, dynamic> json) {
    sending = json["sending"];
    sendError = json["sendError"];
    createdAt = json["createdAt"] != null ? DateTime.fromMillisecondsSinceEpoch(json["createdAt"]) : null;
    updatedAt = json["updatedAt"] != null ? DateTime.fromMillisecondsSinceEpoch(json["updatedAt"]) : null;
    userId = json["userId"];
    viewType = ViewMessageType.from(json["viewType"]);
    section = json["section"] ?? false;
    super.fromJson(json);
  }

  @override
  Map<String, dynamic> toJson() {
    var json = super.toJson();
    json['sending'] = sending;
    json["sendError"] = sendError;
    json["createdAt"] = createdAt?.millisecondsSinceEpoch;
    json["updatedAt"] = updatedAt?.millisecondsSinceEpoch;
    json["userId"] = userId;
    json["viewType"] = viewType?.name;
    json["section"] = section;
    return json;
  }
}

enum ViewMessageType {
  message("MESSAGE"), // 普通消息
  section("SECTION"), // 段
  system("SYSTEM"), // 系统提示
  tips("TIPS"); // 提示

  const ViewMessageType(this.name);
  final String name;

  static ViewMessageType from(String? name) {
    switch (name) {
      case "MESSAGE": return ViewMessageType.message;
      case "SECTION": return ViewMessageType.section;
      case "SYSTEM": return ViewMessageType.system;
      case "TIPS": return ViewMessageType.tips;
    }
    return ViewMessageType.message;
  }
}
